import { Box, TextField, InputAdornment, Button, TableContainer, Table, TableHead, TableRow, Checkbox, TableBody, IconButton, TableFooter } from "@mui/material";
import React, { JSX } from 'react';
import { ReactComponent as SearchIcon } from '../../assets/search.svg';
import { ReactComponent as CreateIcon } from '../../assets/create.svg';
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/Delete';
import ClearIcon from '@mui/icons-material/Clear';
import { removeElementFromArray } from "../../util/Arrays";
import { NulHeaderTableCell, NulTableCell } from "../../components/NulHeaderTable";
import { commodityManagementActions, selectCommodityEntries, selectCommodityEntriesLoaded } from "../../actions/CommodityManagement";
import { useAppSelector, useAppDispatch } from "../../actions/hooks";
import { CommodityEntry } from "../../types";
import { CreateCommodity } from "./CreateCommodity";
import { ModifyCommodity } from "./ModifyCommodity";

function CommodityManagement(): JSX.Element {

  const [filter, setFilter] = React.useState<string>('');
  const [openCommodityDialog, setOpenCommodityDialog] = React.useState<boolean>(false);
  const [openModifyDialog, setOpenModifyDialog] = React.useState<boolean>(false);
  const [modifyCommodityEntry, setModifyCommodityEntry] = React.useState<CommodityEntry>({
    id: 0, name: '', wholesalePrice: 0, retailPrice: 0, costPrice: 0, notes: ''
  });

  const commodityEntriesLoaded = useAppSelector(selectCommodityEntriesLoaded);
  const commodityEntries = useAppSelector(selectCommodityEntries);
  const [checkedIdList, setCheckedIdList] = React.useState<number[]>([]);

  const dispatch = useAppDispatch();

  const handleModify = (row: CommodityEntry) => {
    setModifyCommodityEntry(row);
    setOpenModifyDialog(true);
  };

  const handleDelete = (row: CommodityEntry) => {
    dispatch(commodityManagementActions.deleteCommodity({ id: [row.id] }));
  };

  const handleBatchDelete = () => {
    if (checkedIdList.length > 0) {
      dispatch(commodityManagementActions.deleteCommodity({ id: checkedIdList }));
      setCheckedIdList([]);
    }
  };

  React.useEffect(() => {
    if (!commodityEntriesLoaded) {
      dispatch(commodityManagementActions.getCommodities({ name: filter }));
    }
    setCheckedIdList([]);
  }, [commodityEntriesLoaded, filter, dispatch]);

  React.useEffect(() => {
    dispatch(commodityManagementActions.refresh());
  }, [filter, dispatch]);

  const headerChecked: boolean = checkedIdList.length !== 0 && checkedIdList.length === commodityEntries.length;
  const headerIndeterminate: boolean = checkedIdList.length !== 0 && checkedIdList.length < commodityEntries.length;

  return (
    <>
      <Box sx={{ padding: '30px 30px 30px 30px', flex: 'none', flexGrow: 1, display: 'flex', flexDirection: 'column', height: '100%', boxSizing: 'border-box' }}>
        <Box>
          <Box sx={{
            fontFamily: 'Open Sans',
            fontStyle: 'normal',
            fontWeight: 600,
            fontSize: '22px',
            lineHeight: '125%'
          }}>
            Commodity Management
          </Box>
          <Box sx={{
            marginTop: '20px', width: '100%', height: '40px', display: 'flex',
            flexDirection: 'row', justifyContent: 'space-between'
          }}>
            <Box sx={{ width: '456px' }}>
              <TextField
                size='small'
                fullWidth={true}
                InputProps={{
                  startAdornment: (
                    <InputAdornment position='start' sx={{}}>
                      <SearchIcon />
                    </InputAdornment>
                  ),
                  endAdornment: (
                    <IconButton edge="end" onClick={() => { setFilter(''); }}>
                      <ClearIcon fontSize='small' />
                    </IconButton>
                  )
                }}
                placeholder='Search commodity'
                value={filter}
                onChange={(action) => { setFilter(action.target.value); }}
                sx={{
                  paddingLeft: '0px'
                }}
              />
            </Box>
            <Box sx={{
              flex: 'none',
              order: 1,
              flexGrow: 0
            }}>
              <Button
                variant='contained'
                disableElevation
                startIcon={<DeleteIcon />}
                onClick={handleBatchDelete}
                sx={{
                  height: '40px',
                  textTransform: 'none',
                  marginRight: '10px'
                }}
                color='error'
              >
                Delete
              </Button>
              <Button
                variant="contained"
                disableElevation
                startIcon={<CreateIcon />}
                onClick={() => {
                  setOpenCommodityDialog(true);
                }}
                sx={{
                  height: '40px',
                  textTransform: 'none'
                }}
              >
                Create
              </Button>
            </Box>
          </Box>
        </Box>
        <Box sx={{
          paddingTop: '20px',
          width: '100%',
          flexGrow: 1
        }}>
          <TableContainer
            sx={{
              width: '100%',
              height: '100%'
            }}
          >
            <Table
              stickyHeader
              sx={{
                border: '1px solid #DFE4E8',
                borderRadius: '8px',
                fontFamily: 'Open Sans',
                fontStyle: 'normal',
                display: 'flex',
                flexDirection: 'column',
                height: '100%'
              }}
            >
              <TableHead sx={{ border: '8px 8px 0px 0px' }}>
                <TableRow sx={{
                  height: '42px',
                  padding: 0,
                  width: '100%',
                  display: 'flex',
                  alignItems: 'center',
                }}>
                  <Box sx={{ height: '100%' }}>
                    <NulHeaderTableCell
                      sx={{
                        width: '62px',
                        borderTopLeftRadius: '8px',
                        justifyContent: 'center',
                        flexGrow: 0
                      }}
                    >
                      <Checkbox
                        sx={{
                          width: '42px',
                          display: 'flex',
                          justifyContent: 'center',
                        }}
                        onClick={() => {
                          if (headerChecked) {
                            setCheckedIdList([]);
                          }
                          else {
                            setCheckedIdList(commodityEntries.map(entry => entry.id));
                          }
                        }}
                        checked={headerChecked}
                        indeterminate={headerIndeterminate}
                      />
                    </NulHeaderTableCell>
                  </Box>
                  <Box sx={{ display: 'flex', flexDirection: 'row', flexGrow: 1, position: 'relative', height: '100%' }}>
                    <NulHeaderTableCell sx={{ width: '5%' }}>
                      ID
                    </NulHeaderTableCell>
                    <NulHeaderTableCell sx={{ width: '12%' }}>
                      Name
                    </NulHeaderTableCell>
                    <NulHeaderTableCell sx={{ width: '15%' }}>
                      WholesalePrice
                    </NulHeaderTableCell>
                    <NulHeaderTableCell sx={{ width: '13%' }}>
                      RetailPrice
                    </NulHeaderTableCell>
                    <NulHeaderTableCell sx={{ width: '15%' }}>
                      CostPrice
                    </NulHeaderTableCell>
                    <NulHeaderTableCell sx={{ width: '20%' }}>
                      Address
                    </NulHeaderTableCell>
                    <NulHeaderTableCell sx={{ width: '20%', borderTopRightRadius: '8px', }}>
                      Notes
                    </NulHeaderTableCell>
                  </Box>
                </TableRow>
              </TableHead>
              <TableBody
                sx={{
                  flexGrow: 1, display: 'block', overflowY: 'auto'
                }}
              >
                {commodityEntries.map(row => {
                  const checkedIndex: number = checkedIdList.indexOf(row.id);
                  return (
                    <TableRow
                      key={row.id}
                      sx={{
                        width: '100%',
                        display: 'flex',
                        alignItems: 'center',
                        height: '42px'
                      }}
                    >
                      <Box sx={{ height: '100%' }}>
                        <NulTableCell sx={{ width: '62px', justifyContent: 'center', flexGrow: 0 }}>
                          <Checkbox
                            sx={{
                              width: '42px',
                              display: 'flex',
                              justifyContent: 'center',
                            }}
                            checked={checkedIndex !== -1}
                            onChange={(event, checked) => {
                              if (checked) {
                                if (checkedIndex === -1) {
                                  setCheckedIdList([...checkedIdList, row.id]);
                                }
                              }
                              else {
                                if (checkedIndex !== -1) {
                                  setCheckedIdList(removeElementFromArray(checkedIdList, checkedIndex));
                                }
                              }
                            }}
                          />
                        </NulTableCell>
                      </Box>
                      <Box sx={{ display: 'flex', flexDirection: 'row', flexGrow: 1, position: 'relative', height: '100%' }}>
                        <NulTableCell sx={{ width: '5%' }}>
                          {row.id}
                        </NulTableCell>
                        <NulTableCell sx={{ width: '12%' }}>
                          {row.name}
                        </NulTableCell>
                        <NulTableCell sx={{ width: '15%' }}>
                          {row.wholesalePrice}
                        </NulTableCell>
                        <NulTableCell sx={{ width: '13%' }}>
                          {row.retailPrice}
                        </NulTableCell>
                        <NulTableCell sx={{ width: '15%' }}>
                          {row.costPrice}
                        </NulTableCell>
                        <NulTableCell sx={{ width: '20%' }}>
                          {row.notes}
                        </NulTableCell>
                        <NulTableCell sx={{ width: '20%', display: 'flex' }}>
                          <IconButton aria-label='edit' onClick={() => { handleModify(row); }}>
                            <EditIcon />
                          </IconButton>
                          <IconButton aria-label='delete' onClick={() => { handleDelete(row); }}>
                            <DeleteIcon />
                          </IconButton>
                        </NulTableCell>
                      </Box>
                    </TableRow>
                  );
                })}
              </TableBody>
              <TableFooter
                sx={{
                  minHeight: '34px',
                  maxHeight: '44px',
                  display: 'block',
                  backgroundColor: '#F1F3F5',
                  borderRadius: '0px 0px 8px 8px',
                }}
              ></TableFooter>
            </Table>
          </TableContainer>
        </Box>
      </Box>
      <CreateCommodity
        open={openCommodityDialog}
        onClose={() => { setOpenCommodityDialog(false); }}
      />
      <ModifyCommodity
        open={openModifyDialog}
        onClose={() => { setOpenModifyDialog(false); }}
        commodityEntry={modifyCommodityEntry}
      />
    </>
  )
}

export default CommodityManagement;